import React, { useContext, useState, FunctionComponentElement } from "react";
import { MenuContext } from "./menu";
import ClassNames from "classnames";
import { MenuItemProps } from "./menuItem";
import { CSSTransition } from "react-transition-group";

interface SubItemProps {
  classNames?: string;
  title: string;
  index?: string;
}

const SubItem: React.FC<SubItemProps> = ({
  classNames,
  title,
  index,
  children,
}) => {
  const [isOpen, setOpen] = useState(false);
  const context = useContext(MenuContext);
  const classes = ClassNames("menu-item submenu-item", classNames, {
    "is-active": context.index === index,
  });

  const handleClick = context.mode === 'vertical'? () => {
    setOpen(!isOpen);
  } : () => {};
  let timer:any;
  // fixed 此处的settimeout 有妙用。
  const handleMouse = (e:React.MouseEvent, toggle:boolean) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      setOpen(toggle)
    }, 300)
  }
  const hoverEvent = context.mode !== 'vertical' ?  {
      onMouseEnter: (e: React.MouseEvent) => {handleMouse(e, true)},
      onMouseLeave: (e: React.MouseEvent) => {handleMouse(e, false)}
  }:{};

  const renderChildren = () => {
    const classes = ClassNames("submenu", {
      "menu-opened":  isOpen,
    });
    const childrenComponent = React.Children.map(children, (child, i) => {
      const childElement = child as FunctionComponentElement<MenuItemProps>;
      if (childElement.type.displayName === "MenuItem") {
        return React.cloneElement(childElement, { 
          index:index + '-' + i
        });
      } else {
        console.log("subMenu error");
      }
    });
    return (
      <CSSTransition
        in={isOpen}
        timeout={300}
        classNames="zoom-in-top"
        unmountOnExit
        appear
        >
        <ul className={classes}>{childrenComponent}</ul>
      </CSSTransition>
    )
  };
  return (
    <li className={classes} {...hoverEvent}>
      <div onClick={handleClick}>{title}</div>
      {renderChildren()}
    </li>
  );
};

SubItem.displayName = "SubMenu";
export default SubItem;
